import { _decorator, Component, EventTouch, Input, input, log, Node, UITransform, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('JoyStickManager')
export class JoyStickManager extends Component {

    //让外界访问的值
    public input:Vec2 = Vec2.ZERO
    //摇杆背景
    private body: Node;
    //摇杆轴
    private stick: Node;
    //摇杆默认位置
    private defaultPos: Vec2
    //摇杆半径
    private radius: number

    onLoad () {
        this.body = this.node.getChildByName("Body");
        this.stick = this.body.getChildByName("Stick");
        //获取摇杆半径
        this.radius = this.body.getComponent(UITransform).contentSize.x / 2
        //获取摇杆原始默认位置
        this.defaultPos = new Vec2(this.body.position.x, this.body.position.y)
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onDestroy () {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchStart(e: EventTouch) {
        // console.log(e.getLocation());  // Location on screen space
        console.log(e.getUILocation());  // Location on UI space

        //获取当前点击坐标
        const touchPos = e.getUILocation()
        //设置给摇杆轴让它移动到点击的位置
        this.body.setPosition(touchPos.x, touchPos.y)
    }

    onTouchMove(e: EventTouch) {

        //计算点击的位置是否在摇杆背景里面，如果不是就弹回去
        //计算点击位置的角度，三角函数，夹角

        // const angle = Vec2.angle(touchPos, this.defaultPos)
        // // 将弧度转换为角度
        // const degrees = angle * 180 / Math.PI;
        // console.log('角度:', degrees );

        //获取当前点击坐标
        const touchPos = e.getUILocation()
        const stickPos = new Vec2(touchPos.x - this.body.position.x, touchPos.y - this.body.position.y)
        //判断stack位置是否大于摇杆半径
        if(stickPos.length() > this.radius){
            //向量数乘。将当前向量数乘指定标量，半径除以它的长度
            stickPos.multiplyScalar(this.radius / stickPos.length())
        }
        //设置给摇杆轴让它移动到点击的位置
        this.stick.setPosition(stickPos.x, stickPos.y)

        //输出值,让外界可以访问移动的值，stickPos再归一化(0,1)
        this.input = stickPos.clone().normalize()
    }

    onTouchEnd(e: EventTouch) {
        //还原摇杆位置
        this.body.setPosition(this.defaultPos.x, this.defaultPos.y);
        this.stick.setPosition(Vec2.ZERO.x, Vec2.ZERO.y);
        this.input = Vec2.ZERO
    }

    
}


